#include "./rgba32.h"

static uint8_t rgb32_mix_channel(uint16_t c1, uint16_t c2, uint16_t a) {
    return c1 + (c2 - c1) * a / 255;
}

void rgba32_unpack(uint32_t c, uint8_t channels[4]) {
    channels[RGBA_R_INDEX] = RGBA_UNPACK_R(c);
    channels[RGBA_G_INDEX] = RGBA_UNPACK_G(c);
    channels[RGBA_B_INDEX] = RGBA_UNPACK_B(c);
    channels[RGBA_A_INDEX] = RGBA_UNPACK_A(c);
}

uint32_t rgba32_pack(uint8_t comp[4]) {
    uint32_t color = 0;
    RGBA_PACK_R(color, comp[RGBA_R_INDEX]);
    RGBA_PACK_G(color, comp[RGBA_G_INDEX]);
    RGBA_PACK_B(color, comp[RGBA_B_INDEX]);
    RGBA_PACK_A(color, comp[RGBA_A_INDEX]);
    return color;
}

uint32_t rgba32_mix(uint32_t c1, uint32_t c2) {
    uint8_t rgba1[4];
    rgba32_unpack(c1, rgba1);
    uint8_t rgba2[4];
    rgba32_unpack(c2, rgba2);

    for (int i = 0; i < 3; ++i) {
        rgba1[i] = rgb32_mix_channel(rgba1[i], rgba2[i], rgba2[RGBA_A_INDEX]);
    }

    return rgba32_pack(rgba1);
}